package cn.zs.supply.common.utils;
/*
 * huirong Inc.
 * Copyright (c) 2017 All Rights Reserved.
 * Author     :liyb
 * Create Date:2017年3月21日
 */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.util.Base64;

public class FileUtil {
    private static String ROOT_PATH = ConfigProperties.getProperty("fs.storage.nas.root");
    private static final String y_format="yyyy";
    private static final String m_format="MM";
    private static final String d_format="dd";
   
    
	
	/**
	 * 网上获取文件
	 * 
	 * @param resurl
	 *            资源路径
	 * @param fileName
	 *            自定义资源名
	 */
	public static String downInternetFileForBase64(String picUrl) {
		URL url = null;
		HttpURLConnection con = null;
		InputStream in = null;
		FileOutputStream out = null;
		String res = null;
		try {
			url = new URL(picUrl);
			// 建立http连接，得到连接对象
			con = (HttpURLConnection) url.openConnection();
			in = con.getInputStream();
			byte[] data = getByteData(in);// 转化为byte数组
		    return Base64.encodeBase64String(data);  
		} catch (MalformedURLException e) {
			res = null;
			e.printStackTrace();
		} catch (IOException e) {
			res = null;
			e.printStackTrace();
		} finally {
			try {
				if (null != out)
					out.close();
				if (null != in)
					in.close();
			} catch (IOException e) {
				res = null;
				e.printStackTrace();
			}
		}
		return res;
	}
	/**
     * 从输入流中获取字节数组
     * 
     * @param in
     * @return
     * @throws IOException
     */
	private static byte[] getByteData(InputStream in) throws IOException {
		byte[] b = new byte[1024 * 10];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int len = 0;
		while ((len = in.read(b)) != -1) {
			bos.write(b, 0, len);
		}
		if (null != bos) {
			bos.close();
		}
		return bos.toByteArray();
	}
	
    /**
     * 设置目标文件路径
     * @return
     */
    public static String getTargetPath(){
        Date date = new Date();
        String year = DateUtil.formatDate(date, y_format);
        String month = DateUtil.formatDate(date, m_format);
        String day = DateUtil.formatDate(date, d_format);
        return "/"+year+"/"+month+"/"+day;
    }
    
	public static File createFile(String path) throws IOException{
		File file = new File(path); 
		File fileParent = file.getParentFile(); 
		if(!fileParent.exists()){ 
		  fileParent.mkdirs(); 
		} 
		file.createNewFile();
		return file;
	}
	/**
	 * 识别txt文件编码格式
	 * @param fileName 
	 * @return
	 * @throws IOException
	 */
	public static String getCharset(String fileName) throws IOException {
        
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
        int p = (bin.read() << 8) + bin.read();    
          
        String code = null;
          
        switch (p) {    
            case 0xefbb:    
                code = "UTF-8";    
                break;    
            case 0xfffe:    
                code = "Unicode";    
                break;    
            case 0xfeff:    
                code = "UTF-16BE";    
                break;    
            default:    
                code = "GBK";    
        }    
        return code;  
	}  

    /**
     * 删除文件
     * @param file
     * @return 
     */
    public static boolean deleteFile(File file) {
    		if (file.isDirectory()) {
                String[] children = file.list();
                for (int i=0; i<children.length; i++) {
                    boolean success = deleteFile(new File(file, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }
            // 目录此时为空，可以删除
            return file.delete();
    }
    
    /**
	 * 拷贝文件
	 * 
	 * @param sourceFile
	 * @param newFile
	 */
	public static void copyFile(File sourceFile, File newFile) {
		File nf = newFile;
		File sf = sourceFile;
		nf.mkdirs();
		if (nf.exists())
			nf.delete();

		try {
			FileInputStream input = new FileInputStream(sf);
			BufferedInputStream inBuff = new BufferedInputStream(input);

			FileOutputStream output = new FileOutputStream(nf);
			BufferedOutputStream outBuff = new BufferedOutputStream(output);

			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			outBuff.flush();
			inBuff.close();
			outBuff.close();
			output.close();
			input.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * NIO进行快速的文件拷贝
	 * @param in 源文件
	 * @param out 输入文件
	 */
	public static void fileCopy(File in, File out){
	    out.mkdirs();
        if (out.exists()){
            out.delete();
        }
	    FileChannel inChannel = null;
	    FileChannel outChannel = null;
	    try {
	        inChannel = new FileInputStream(in).getChannel();
	        outChannel = new FileOutputStream(out).getChannel();
	        int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while (position<size){
                position += inChannel.transferTo(position, maxCount, outChannel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(inChannel!=null){
                try {
                    inChannel.close();
                } catch (IOException e) {}
            }
            if(outChannel!=null){
                try {
                    outChannel.close();
                } catch (IOException e) {}
            }
        }
	}
	
	/**
	 * 删除指定文件夹下的所有文件夹和文件
	 * @param path
	 * @return
	 */
	public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }
	
	/**
     * 删除文件夹
     * @param folderPath
     */
    private static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @SuppressWarnings("resource")
	public static String readFile(File file){
		BufferedReader reader = null;
		StringBuffer buffer = new StringBuffer();
		try {
			String charSet = EncodingDetect.getJavaEncode(file.getAbsolutePath());
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));
		    String tempString = "";
			while (( tempString = reader.readLine()) != null) {  
		    	buffer.append(tempString); 
		    	buffer.append("\n"); 
		    }
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return buffer.toString();  

	}
    
    /**
     * 删除指定的文件
     * @param _sourceFile 被删除的文件
     * @param _thumFile 被删除的缩略图文件
     * @return
     */
    public static boolean rmFixedFile(String _sourceFile, String _thumFile){
        boolean bool = true;
        try {
            if(StringUtils.isNotEmpty(_sourceFile)){
                File file = new File(ROOT_PATH+_sourceFile);
                file.delete();
            }
            if(StringUtils.isNotEmpty(_thumFile)){
                File file = new File(ROOT_PATH+_thumFile);
                file.delete();
            }
        } catch (Exception e) {
            bool = false;
            e.printStackTrace();
        }
        return bool;
    }
    
    /**
     * 删除某个文件夹下的所有文件夹和文件
     * @param folder 文件目录
     * @return
     */
    public static void rmFolderFile(String folder){
        try {
            File file = new File(folder);
            if (!file.isDirectory()) {
                file.delete();
            } else{
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File delfile = new File(folder + "/" + filelist[i]);
                    if (!delfile.isDirectory()) {
                        delfile.delete();
                    }else{
                        rmFolderFile(folder + "" + filelist[i]);
                    }
                }
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * base64字符串转化成图片
     * @param imageBase64Str 图片base64字符串
     * @return 返回生成的文件对象
     */
    public static String generateImage(byte[] photo,String orderNo) {
        File file=null;
        OutputStream out = null;
        //对字节数组字符串进行Base64解码并生成图片
        if (photo == null) //图像数据为空
            return null;
        try {
            //生成jpeg图片
            String imgFilePath =ConfigProperties.getProperty("fs.storage.nas.root")
        			+FileUtil.getTargetPath()+orderNo+String.valueOf(System.currentTimeMillis())+new Random().nextInt()+".jpg";
            out = new FileOutputStream(imgFilePath);
            out.write(photo);
            out.flush();
            file = new File(imgFilePath);
            return imgFilePath;
        } catch (Exception e) {
            return null;
        } finally {
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {}
            }
        }
    }
    
    /**
	 * 生成报告编号
	 * 格式：年月日+（时分秒毫秒+4位随机数）转为为36进制
	 * 示例：20161214ARLRQZHE
	 * @return
	 */
	public static String generateNumber() {
		String reportId = "";
		try {
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat sdf1 = new SimpleDateFormat("hhmmssSSS");
			String dateresult = sdf.format(date);
			String datess = sdf1.format(date);
			// 产生四位数的随机数
			int number = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;
			String num = datess + number;
			String base = baseMath(num);// 转化36进制 时分秒毫秒四位随机数转化为36进制
			// 生成唯一的编号
			reportId = dateresult + base;
		} catch (Exception e) {
			reportId = "";
			e.printStackTrace();
		}
		return reportId;
	}
	
	/**
	 * 生成36进制码
	 * 
	 * @param num
	 * @return
	 */
	public static String baseMath(String num) {
		boolean prefix = false;
		if (num.substring(1).equals("0")) {
			prefix = true;
			num = num.substring(1, num.length() - 1);
		}
		List lists = new ArrayList();
		char[] list = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8',
				'9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
				'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z' };
		Long sum = Long.parseLong(num);
		int account = 36;
		while (true) {
			Integer Index = (int) (sum % account);
			sum = sum / account;
			char str = list[Index];
			lists.add(list[Index]);
			if (sum == 0)
				break;
		}
		String numb = "";
		for (int i = 0; i < lists.size(); i++) {
			numb = numb + lists.get(i);
		}
		return (prefix ? '0' : "") + numb;
	}
	

}
